package com.heima.datasync.service.imp;

import com.google.common.collect.Lists;
import com.heima.datasync.mapper.ApArticleMapper;
import com.heima.datasync.service.EsDataService;
import com.heima.es.service.EsService;
import com.heima.model.article.pojo.ApArticle;
import com.heima.model.common.constants.es.EsIndexConstance;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.vos.SearchArticleVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class EsDataServiceImpl implements EsDataService {
    @Autowired
    EsService esService;
    @Autowired
    ApArticleMapper apArticleMapper;
    @Override
    public ResponseResult dataInit() {
        //1.判断索引库存不存在
        boolean existIndex = esService.existIndex(EsIndexConstance.IndexName);
        //2.如果索引库存在 删除创建 不存在创建
        if (existIndex) {
            esService.deleteIndex(EsIndexConstance.IndexName);
        }
        //3.从数据库获取文章数据
        esService.createIndex(EsIndexConstance.IndexMapping,EsIndexConstance.IndexName);
        //4.查询数据库文章的集合  将集合转变成想要的集合
        List<ApArticle> allArticles = apArticleMapper.findAllArticles();
        List<SearchArticleVO> searchArticleVOList =
                allArticles.stream().map(apArticle -> {
            SearchArticleVO searchArticleVO = new SearchArticleVO();
            BeanUtils.copyProperties(apArticle, searchArticleVO);
            //将查询的文章类转换成es需要的实体类
            return searchArticleVO;
        }).collect(Collectors.toList());
        //5.批量保存文章数据到es索引库  5000
        List<List<SearchArticleVO>> partition = Lists.partition(searchArticleVOList, 5000);
        //循环将文章的值插入到索引库
        for (List<SearchArticleVO> searchArticleVOS : partition) {
            esService.saveBatch(searchArticleVOS,EsIndexConstance.IndexName);
        }
        return ResponseResult.okResult();
    }
}
